// pages/message/chat/chat.js
const App = getApp();
const utils = require('../../../utils/util.js')
var JIM = App.globalData.jim
Page({

  /**
   * 页面的初始数据
   */
  data: {
    height:0,
    messageList:[],
    faceUrl:wx.getStorageSync('faceUrl'),
    name:'',
    content:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      name:options.name,
      xdId:options.id,
      title:options.title,
      price:options.price,
      toyspic:options.toyspic
    })
    // 获取当前窗口的高度
    var height = (wx.getSystemInfoSync().windowHeight) - 55 + 'px'
    this.setData({
      height:height
    })

    this.getMessage();
    this.getSelfInfo();
    this.getUserInfo();
  },
  //获取用户信息
  getUserInfo:function (){
    var that = this;
    utils.requestUrl({//将用户信息传给后台数据库
      // method:'post',
      url: "/niu/apiv3/member_userinfo.php",
      params: {
        markid: wx.getStorageSync('markId'),
      }
    }).then((res) => {
      // console.log(res)
      that.setData({
        faceUrl:res.data.data.faceurl
      })
    })
  },
  //获取个人信息
  getSelfInfo:function () {
    var that = this;
    var name = this.data.name;
    utils.getSelfInfo(name).then(function(successData) {
      // arr[j].imgUrl = successData
      // console.log(successData)
      wx.setNavigationBarTitle({
        title: successData.nickname 
      })

      utils.getResource(successData.avatar).then(function(successData) {
        that.setData({
          userAvatar:successData
        })
      })

    })
  },

  //获取消息
  getMessage:function () {
    var that = this;
    var name = this.data.name;
    //获取离线消息
    // var onSyncConversationList = App.globalData.onSyncConversation;
    var onSyncConversationList = wx.getStorageSync(name);
    // console.log(onSyncConversationList);
    that.listArr(onSyncConversationList)

    //消息实时监听
    JIM.onMsgReceive(function(data) {
      // console.log(data)
      var onSyncConversationList = wx.getStorageSync(name);
      for (var i = 0;i < data.messages.length;i++){
        var msg = wx.getStorageSync(data.messages[i].from_username);
        msg.push(data.messages[i])
        wx.setStorageSync(data.messages[i].from_username, msg)

        if (data.messages[i].from_username == name){
          onSyncConversationList.push(data.messages[i])
        }

      }
      that.listArr(onSyncConversationList)
      wx.setStorageSync(name, onSyncConversationList)
     
   });
   
  },
  //处理消息数据
  listArr:function (listArr) {
    // console.log(listArr);
    var msg_ids = new Array;
    var that = this;
    var name = this.data.name;
    var arr = [];//截取数据
    if (listArr == undefined){
      return
    }

    for(var i = 0; i < listArr.length;i++){
      msg_ids.push(listArr[i].msg_id);
      var time;

      if(i == 0){
        time = utils.getTsFormatDate(listArr[i].content.create_time)
      }else{
        if((listArr[i].content.create_time - listArr[i-1].content.create_time) > 60000){
          time = utils.getTsFormatDate(listArr[i].content.create_time)
        }else{
          time = ''
        }
      }

      if (listArr[i].content.msg_type == 'text'){
        //判断消息是否是本人发出
        if(listArr[i].content.from_id == name){
          
          arr.push({userId:listArr[i].content.from_id.substring(7),time:time,from_id:0,msg_type:listArr[i].content.msg_type,text:listArr[i].content.msg_body.text})
          
        }else{
          arr.push({userId:listArr[i].content.from_id.substring(7),time:time,from_id:1,msg_type:listArr[i].content.msg_type,text:listArr[i].content.msg_body.text})
        }
        
      }else if (listArr[i].content.msg_type == 'image'){

        //判断消息是否是本人发出
        if(listArr[i].content.from_id == name){
          arr.push({userId:listArr[i].content.from_id.substring(7),time:time,from_id:0,msg_type:listArr[i].content.msg_type,imgUrl:'https://img1.odancool.com/defaultface001.jpg',imgUrlId:listArr[i].content.msg_body.media_id})
        }else{
  
          arr.push({userId:listArr[i].content.from_id.substring(7),time:time,from_id:1,msg_type:listArr[i].content.msg_type,imgUrl:'https://img1.odancool.com/defaultface001.jpg',imgUrlId:listArr[i].content.msg_body.media_id})
        }
        
      }else if (listArr[i].content.msg_type == 'custom'){
        if(listArr[i].content.from_id == name){
          arr.push({userId:listArr[i].content.from_id.substring(7),time:time,from_id:0,msg_type:listArr[i].content.msg_type,xdid:listArr[i].content.msg_body.xdid,title:listArr[i].content.msg_body.title,price:listArr[i].content.msg_body.price,toyspic:listArr[i].content.msg_body.toyspic})
        }else{
  
          arr.push({userId:listArr[i].content.from_id.substring(7),time:time,from_id:1,msg_type:listArr[i].content.msg_type,xdid:listArr[i].content.msg_body.xdid,title:listArr[i].content.msg_body.title,price:listArr[i].content.msg_body.price,toyspic:listArr[i].content.msg_body.toyspic})
        }
          
      }
    }

    //获取图像资源
    for (let j = 0;j < arr.length;j++){
      utils.getResource(arr[j].imgUrlId).then(function(successData) {
        arr[j].imgUrl = successData
      })
    }
    // console.log(arr);
   setTimeout(function(){
    that.setData({
      messageList:arr,
      msg_ids:msg_ids,
      toView: "msg-" + (arr.length - 1),
    })
   },300)
  },
  //input中的数据
  contentInput:function (e) {
    var content = e.detail.value;
    this.setData({
      content:content
    })
  },
  //查看是否在黑名单
  isBlack:function (chatType){
    var that = this;
    var tousername = that.data.name;
    var userId = tousername.substring(7);
    utils.requestUrl({//将用户信息传给后台数据库
      // method:'post',
      url: "/niu/apiv3/weibo_blackuser.php?method=itemcheck",
      params: {
        markid: wx.getStorageSync('markId'),
        blockuserid:userId
      }
    }).then((res) => {
      console.log(res.data);
      this.setData({
        isblock:res.data.isblock
      })
      if(res.data.isblock == 1){
        utils.toast('双方处于黑名单状态')
      }else{
        if(chatType == 0){
          var content = that.data.content;
          if (content == ''){
            utils.toast('发送内容不能为空')
            return
          }else{
            that.isWJC(content)
          }
        }else if(chatType == 1){
          //先通过小程序API获取图片
          wx.chooseImage({
            count: 1, //
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              // console.log(res)
              var tempFilePaths = res.tempFilePaths[0]; //获取成功，读取文件路径
              JIM.sendSinglePic({
                'target_username' : tousername,
                'image' : tempFilePaths //设置图片参数
              }).onSuccess(function(data,msg) {
                var onSyncConversationList = wx.getStorageSync(tousername);
                onSyncConversationList.push(msg)
                wx.setStorageSync(tousername, onSyncConversationList)
                that.listArr(onSyncConversationList)
              }).onFail(function(data) {
                // console.log(data)
                utils.toast('图片发送失败,请稍后再试');
              });
            }
          })
        }else if(chatType == 2){
          //先通过小程序API获取图片
          wx.chooseImage({
            count: 1, //
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              console.log(res)
              var tempFilePaths = res.tempFilePaths[0]; //获取成功，读取文件路径
              JIM.sendSinglePic({
                'target_username' : tousername,
                'image' : tempFilePaths //设置图片参数
              }).onSuccess(function(data,msg) {
                console.log(data);
                var onSyncConversationList = wx.getStorageSync(tousername);
                onSyncConversationList.push(msg)
                wx.setStorageSync(tousername, onSyncConversationList)
                that.listArr(onSyncConversationList)
              }).onFail(function(data) {
                // console.log(data)
                utils.toast('图片发送失败,请稍后再试');
              });
            }
          })
        }else if(chatType == 4){
          var tousername = that.data.name;
          var xdId = that.data.xdId;
          var title = that.data.title;
          var price = that.data.price;
          var toyspic = that.data.toyspic;
          var custom = {
            'xdid':xdId,
            'title':title,
            'price':price,
            'toyspic':toyspic
          };
          JIM.sendSingleCustom({
            'target_username' : tousername,
            'custom' : custom,
          }).onSuccess(function(data , msg) {
            var onSyncConversationList = wx.getStorageSync(tousername);
            // console.log(onSyncConversationList)
            if (onSyncConversationList == ''){
              onSyncConversationList = new Array;
            }
            onSyncConversationList.push(msg)
            wx.setStorageSync(tousername, onSyncConversationList)
            that.listArr(onSyncConversationList)
          }).onFail(function(data) {
            //同发送单聊文本
          });
        }
      }
    })
  },
  //查看是否有违禁词
  isWJC:function (words){
    var that = this;
    var tousername = that.data.name;
    var userId = tousername.substring(7);
    utils.requestUrl({//将用户信息传给后台数据库
      // method:'post',
      url: "/niu/apiv3/weibo_blackuser.php?method=checkwords",
      params: {
        markid: wx.getStorageSync('markId'),
        blockuserid:userId,
        words:words
      }
    }).then((res) => {
      console.log(res.data);
      if (res.data.resultcode == '0'){
        // 发送消息
        JIM.sendSingleMsg({
          'target_username' : tousername,
          'content' : words,
        }).onSuccess(function(data,msg) {
          var onSyncConversationList = wx.getStorageSync(tousername);
          // console.log(onSyncConversationList)
          if (onSyncConversationList == ''){
            onSyncConversationList = new Array;
          }
          onSyncConversationList.push(msg)
          wx.setStorageSync(tousername, onSyncConversationList)
          that.listArr(onSyncConversationList)
          
          that.setData({
            content:''
          })
        }).onFail(function(data) {
          utils.toast('消息发送失败');
          this.setData({
            content:''
          })
        });
      }else{
        utils.toast(res.data.msg)
      }
    })
  },
  //发送单聊文本
  sendMsg:function () {
    var that = this;
    that.isBlack('0');
  },
  //拍摄图片并发送
  photoPic:function () {
    var that = this;
    that.isBlack('1');
  },
  sendPic:function () {
    var that = this;
    that.isBlack('2');
  },
  //自定义消息发送
  sendSingleCustom:function () {
    var that = this;
    that.isBlack('4');
  },

  //自定义消息调往咸蛋
  goToUsedDetail:function (e) {
    let id = e.currentTarget.dataset.xdid;
    wx.navigateTo({
      url: '/pages/used/usedDetail/usedDetail?id='+id+'&sourt=chat',
    })
  },
  goToIndex:function (e){
    let id = e.currentTarget.dataset.userid;
    console.log(id)
    wx.navigateTo({
      url: '/pages/my/myIndex/myIndex?userId='+id,
    })
  },
  //预览图片
  previewImage:function (e) {
    var current = e.currentTarget.dataset.src;
    var urls = new Array;
    urls.push(current);
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
   /**
   * 长按复制
   */
  copy: function (e) {
    // console.log(e);
    var data = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: data,
      success: function (res) {
        utils.toast('复制成功')
      }
    });
  },
   

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var xdId = this.data.xdId;
    if (xdId != undefined){
      this.sendSingleCustom();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
     // 重置单聊会话，调用则成功，无回调函数
     var name = this.data.name;
    JIM.resetUnreadCount({
      'username' : name
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})